import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Description: 创建 RabbitMQProducer 类，使用 Channel 发送消息。
 * @Author: LiuZiHao
 * @Date: 2022/5/6 10:12
 */
public class RabbitMqProducer {
    private static final String IP_ADDRESS = "127.0.0.1";
    private static final Integer PORT = 5672;
    private static String USERNAME = "guest";
    private static String PASSWORD = "guest";

    private static final String EXCHANGE_NAME = "exchange_demo";
    private static final String ROUTING_KEY = "routingkey_demo";
    /**
     * 只有 QUEUE_NAME 需要 共享给 RabbitMqConsumer
     */
    public static final String QUEUE_NAME = "queue_demo";

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接
        Connection conn = getConnection();
        //创建信道
        Channel channel = conn.createChannel();
        //初始化测试用的Exchange 和 Queue
        initExchangeAndQueue(channel);
        //发送消息
        for (int i = 0; i < 3; i++) {
            String message = "Hello World" + i;
            channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
        }
        //close
        channel.close();
        conn.close();
    }

    /**
     * 创建RabbitMq Exchange 和 Queue , 然后使用ROUTING_KEY 路由键将两者绑定.
     * 该步骤,其实可以在RabbitMq Management 上操作 ， 并不一定需要在代码中
     *
     * @param channel
     */
    private static void initExchangeAndQueue(Channel channel) throws IOException {
        //创建交换机 direct,持久化，不自动删除
        channel.exchangeDeclare(EXCHANGE_NAME, "direct", true, false, null);
        //创建队列:持久化，非排他，非自动删除的队列
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        //将交换器与队列通过路由键绑定
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);
    }

    public static Connection getConnection() {
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(IP_ADDRESS);
            factory.setPort(PORT);
            factory.setUsername(USERNAME);
            factory.setPassword(PASSWORD);
            return factory.newConnection();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (TimeoutException e) {
            e.printStackTrace();
            return null;
        }
    }
}
